package com.wx.config;

import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author wuweifeng wrote on 2017/10/31.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryWx", transactionManagerRef = "transactionManagerWx", basePackages = { "com.wx.repository.wxRepository" })
public class WxDbConfig {

	@Resource
	@Qualifier("wxDataSource")
	private DataSource wxDataSource;

	@Primary
	@Bean(name = "entityManagerWx")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryWx(builder).getObject().createEntityManager();
	}

	@Resource
	private JpaProperties jpaProperties;

	private Map<String, Object> getVendorProperties() {
		return jpaProperties.getHibernateProperties(new HibernateSettings());
	}

	/**
	 * 设置实体类所在位置
	 */
	@Primary
	@Bean(name = "entityManagerFactoryWx")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryWx(EntityManagerFactoryBuilder builder) {

		return builder.dataSource(wxDataSource).packages("com.wx.model.wxDb")
				// 使用该entityManagerFactory所用名调用
				.persistenceUnit("wxPersistenceUnit").properties(getVendorProperties()).build();
	}

	@Primary
	@Bean(name = "transactionManagerWx")
	public PlatformTransactionManager transactionManagerWx(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryWx(builder).getObject());
	}

}